package com.njworkorder.Controller;

import cn.microvideo.qsc.client.entity.Role;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.njworkorder.DTO.MenuAddDto;
import com.njworkorder.Entity.Menu;
import com.njworkorder.Entity.RoleMenu;
import com.njworkorder.HTSingleLogin.SecurityUtils;
import com.njworkorder.Service.MenuService;
import com.njworkorder.Service.RoleMenuService;
import com.njworkorder.Service.RoleService;
import com.njworkorder.Utils.Result;
import com.njworkorder.Utils.ResultUtil;
import com.njworkorder.VO.MenuLevelVo;
import com.njworkorder.adapter.QsApiAdapter;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Tag(name = "菜单管理", description = "菜单管理相关接口")
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Resource
    QsApiAdapter qsApiAdapter;

    private final MenuService menuService;
    private final RoleMenuService roleMenuService;
    private final RoleService roleService;
    public MenuController(MenuService menuService,RoleMenuService roleMenuService,RoleService roleService) {
        this.menuService = menuService;
        this.roleMenuService = roleMenuService;
        this.roleService = roleService;
    }

    @Operation(summary = "添加菜单")
    @PostMapping("/addInfo")
    public Result<String> addInfo(@RequestBody MenuAddDto menuAddDto){
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuAddDto,menu);
        boolean save = menuService.save(menu);
        if (save){
            return ResultUtil.success("添加成功");
        }
        return ResultUtil.fail("添加失败");
    }

    @Operation(summary = "根据id删除菜单")
    @GetMapping("/deleteById")
    public Result<String> deleteInfo(@RequestParam("id") String id){
        boolean removeById = menuService.removeById(id);
        if (removeById){
            return ResultUtil.success("删除成功");
        }
        return ResultUtil.fail("删除失败");
    }

    @Operation(summary = "根据id修改菜单")
    @PostMapping("/updateById/{id}")
    public Result<String> updateInfo(@RequestBody MenuAddDto menuAddDto,@PathVariable("id") String id){
        Menu menu = new Menu();
        BeanUtils.copyProperties(menuAddDto,menu);
        menu.setId(id);

        boolean updateById = menuService.updateById(menu);
        if (updateById){
            return ResultUtil.success("修改成功");
        }
        return ResultUtil.fail("修改失败");
    }


    @Operation(summary = "获取菜单层级关系",description = "可以根据角色id查询角色已选菜单")
    @GetMapping("/getMenuLevelRelationship")
    public Result<List<MenuLevelVo>> getMenuLevelRelationship(@RequestParam(value = "roleId",required = false) String roleId,
                                                              @Schema(description = "1,查询所传角色在菜单中的选择情况，2,查询所传角色拥有的菜单")
                                                              @RequestParam(value = "type",required = false,defaultValue = "1") String type){

        List<String> roleIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(roleId)){
            roleIds = Arrays.stream(roleId.split(",")).toList();
        }

        MPJLambdaWrapper<Menu> queryWrapper = new MPJLambdaWrapper<Menu>()
                .eq(Menu::getStatus,2)
                .orderByAsc(Menu::getPublishTime);
        if (type.equals("2")) {
            queryWrapper.leftJoin(RoleMenu.class,RoleMenu::getMenuId,Menu::getId)
                    .in(RoleMenu::getRoleId,roleIds);
        }
        List<Menu> list = menuService.selectJoinList(Menu.class, queryWrapper);
        if(!list.isEmpty()){
            list = list.stream().distinct().collect(Collectors.toList());
        }

        List<String> MenuIds = new ArrayList<>();
        if(StringUtils.isNotEmpty(roleId) && type.equals("1")){
            LambdaQueryWrapper<RoleMenu> Wrapper = new LambdaQueryWrapper<RoleMenu>()
                    .select(RoleMenu::getMenuId)
                    .in(RoleMenu::getRoleId,roleIds);
            MenuIds = roleMenuService.list(Wrapper).stream().map(RoleMenu::getMenuId).toList();
        }

        List<Menu> listFirst = list.stream().filter(menu -> menu.getParentId().isEmpty() || menu.getParentId().isBlank() || menu.getSort().equals(1)).toList();
        List<MenuLevelVo> listRes = new ArrayList<>();
        MenuLevelVo menuLevelVo;
        for (Menu menu : listFirst) {
            menuLevelVo = new MenuLevelVo();
            BeanUtils.copyProperties(menu,menuLevelVo);
            if(MenuIds.contains(menu.getId()) || type.equals("2")){
                menuLevelVo.setSelected(true);
            }
            menuLevelVo.setSubset(getSubset(menu.getId(),list,MenuIds,type));
            listRes.add(menuLevelVo);
        }

        return  ResultUtil.success(listRes);
    }


    @Operation(summary = "获取登录人员角色菜单信息")
    @GetMapping("/getUserMenu")
    public Result<List<MenuLevelVo>> getUserMenu() {
        LambdaQueryWrapper<com.njworkorder.Entity.Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(com.njworkorder.Entity.Role::getId,com.njworkorder.Entity.Role::getRoleName);
        List<com.njworkorder.Entity.Role> list = roleService.list(queryWrapper);

        String userId = SecurityUtils.getUserId();
        //String userId = "18083770499";
        List<Role> personRole = qsApiAdapter.findPersonRole(userId);
        List<com.njworkorder.Entity.Role> roleWithSameNames = findRoleWithSameNames(list, personRole);
        if(roleWithSameNames.isEmpty()){
            return ResultUtil.fail(userId + "无权限进入长周期系统！");
        }

        String collect = roleWithSameNames.stream().map(com.njworkorder.Entity.Role::getId).collect(Collectors.joining(","));
        Result<List<MenuLevelVo>> menuLevelRelationship = getMenuLevelRelationship(collect, "2");
        List<MenuLevelVo> data = menuLevelRelationship.getData();
        if(data == null || data.isEmpty()){
            return ResultUtil.fail("长周期系统未为该角色分配菜单！");
        }

        return ResultUtil.success(data);
    }



    private List<com.njworkorder.Entity.Role> findRoleWithSameNames(List<com.njworkorder.Entity.Role> role1, List<Role> role2) {
        // 1. 提取所有User的姓名到一个Set中
        Set<String> userNames = role2.stream()
                .map(Role::getName)
                .collect(Collectors.toSet());

        // 2. 过滤People列表，只保留姓名在userNames中存在的People
        return role1.stream()
                .filter(f -> userNames.contains(f.getRoleName()))
                .collect(Collectors.toList());
    }

    private static List<MenuLevelVo> getSubset(String id, List<Menu> list,List<String> MenuIds,String type) {
        List<Menu> list1 = list.stream().filter(menu -> menu.getParentId().equals(id)).toList();
        List<MenuLevelVo> listRes = new ArrayList<>();
        if (!list1.isEmpty()) {
            MenuLevelVo menuLevelVo;
            for (Menu menu : list1) {
                menuLevelVo = new MenuLevelVo();
                BeanUtils.copyProperties(menu,menuLevelVo);
                if(MenuIds.contains(menu.getId()) || type.equals("2")){
                    menuLevelVo.setSelected(true);
                }
                menuLevelVo.setSubset(getSubset(menu.getId(),list,MenuIds,type));
                listRes.add(menuLevelVo);
            }
        }
        return listRes;
    }

}
